import {createRouter, createWebHashHistory} from "vue-router";

import home from "../page/home.vue"
import login from "../page/login.vue"
import register from "../page/register.vue"
import buyCar from "../page/buyCar.vue"
import carItem from "../page/carItem.vue"
import sellCar from "../page/sellCar.vue"
import shop from "../page/shop.vue"
import user from "../page/user.vue"
import userCollect from "../page/user/userCollect.vue"
import userConfig from "../page/user/userConfig.vue"
import userInfo from "../page/user/userInfo.vue"
import {getUserState} from "../storage/storage";

const routes = [
    {
        path:"/",
        redirect:"/home"
    },
    {
        path:"/home",
        name:"home",
        component:home
    },
    {
        path:"/login",
        name:"login",
        component:login
    },
    {
        path:"/register",
        name:"register",
        component:register
    },
    {
        path:"/buyCar",
        name:"buyCar",
        component: buyCar
    },
    {
        path:"/carItem",
        name:"carItem",
        component: carItem
    },
    {
        path:"/sellCar",
        name:"sellCar",
        component: sellCar
    },
    {
        path:"/shop",
        name:"shop",
        component:shop
    },
    {
        path:"/user",
        name:"user",
        component: user,
        redirect: "/userInfo",
        children:[
            {
                path:"/userCollect",
                name:"userCollect",
                component: userCollect
            },
            {
                path:"/userConfig",
                name:"userConfig",
                component: userConfig
            },
            {
                path:"/userInfo",
                name:"userInfo",
                component: userInfo
            }
        ]
    }
]

const router = createRouter({
    mode:"history",
    history:createWebHashHistory(),
    routes:routes,
})

router.beforeEach((to) =>{
    if (to.path === "/register" || to.path === "/login"){
        if (getUserState()){
            return false;
        }
    }else if (to.path === "/carInfo" || to.path === "/user" || to.path === "/userCollect" || to.path === "/userConfig" || to.path === "/userConfig"){
        if (!getUserState()){
            return {name:"login"};
        }else {
            return true;
        }
    }
})

export default router
